/**
 * Beaver - Zend/Ext.Direct framework
 * http://code.google.com/p/beaverfw
 *
 * @license     http://www.gnu.org/licenses/gpl-2.0.txt
 * @author      Mihály Kuprivecz <mkuprivecz@gmail.com>
 * @namespace   Beaver
 */

/**
 * Create console pseudo object when firebug is disabled/not installed
 */
if ( !window.console ) window.console = {};
for ( fn in {
        // maximum possible console functions based on firebug
        log: null , debug: null, info: null, warn: null, error: null, assert: null, dir: null, dirxml: null, group: null,
        groupEnd: null, time: null, timeEnd: null, count: null, trace: null, profile: null, profileEnd: null
    } )
{
    window.console[fn] = window	.console[fn] || function() {};
}

Ext.ns('Beaver.Modules');
Ext.ns('Beaver.Loader');
Ext.ns('Beaver.Loader.UI');


/**
 * Add Exception event handling to Application
 * Show an error message, when ajax request failed
 * @param {Object} event
 */
Ext.Direct.on('exception', function( event )
{
	Ext.Msg.show({
	   title: 'Exception: ' + event.message,
	   msg:   event.where
	});
});

Beaver.applicationStarted = false;

/**
 * progressbar element for the loader
 */
Beaver.Loader.UI.progressBar = new Ext.ProgressBar({
	text:'Initializing...',
	animate : true
});

/**
 * Container element of the loader 
 */
Beaver.Loader.UI.window = new Ext.Window({
		layout:    'fit',
		width:     300,
		modal:     true,
		closable:  false,
		resizable: false,
		plain:     true,
		border:    false,
		items:     Beaver.Loader.UI.progressBar
});

/**
 * Stack of the the queue modules
 */
Beaver.Loader.modules       = [];

/**
 * Count of the queued modules before start load the queue 
 */
Beaver.Loader.originalCount = 0;

/**
 * Callback method, it's call when loading ended 
 */
Beaver.Loader.callback      = function(){};

/**
 * Load a module by id
 * @param {String} id
 * @param {Function} callback
 */
Beaver.Loader.loadModule = function( id, callback ) {
	if ( callback == null ) var callback = function(){}; 
	$.ajax({
		url: "module/" + id +"/index/",
		dataType : 'script',
		success : callback,
		error :	function(){
			Ext.Msg.alert('Error', id + ' Module loading failed!')
		}
	});
};

/**
 * Add module to the queue list
 * @param {String} id
 */
Beaver.Loader.addModuleToQueue = function(id)
{
	Beaver.Loader.modules.push(id);
	Beaver.Loader.originalCount++;
};

/**
 * Loader of the next module
 */
Beaver.Loader.loadNextOnQueue = function()
{
	id = Beaver.Loader.modules.shift();
	if ( typeof(id) == "undefined")
	{
		// no more mododule to load
		// timeout is need for the progressbar animation
		setTimeout( function(){
			Beaver.Loader.UI.window.hide();
			Beaver.Loader.UI.progressBar.reset();
			Beaver.Loader.originalCount = 0;
			Beaver.Loader.callback();
		}, 1000 );
		return;
	}
	var percent = Math.round( - (Beaver.Loader.modules.length - Beaver.Loader.originalCount) / Beaver.Loader.originalCount * 100 );
	Beaver.Loader.UI.progressBar.updateProgress(percent/100, percent+'% <?php echo $this->beaverLanguage->get("Beaver","completed") ?>...');
	Beaver.Loader.loadModule(id, Beaver.Loader.loadNextOnQueue);
};

/**
 * Start to load the queue list
 * @param {Function} callback
 */
Beaver.Loader.start = function( callback )
{
	if ( typeof(callback) != "undefined" ) Beaver.Loader.callback = callback;
	Beaver.Loader.UI.window.show();
	Beaver.Loader.originalCount = Beaver.Loader.modules.length;
	Beaver.Loader.loadNextOnQueue();
};

/**
 * Start the Beaver Application
 */
Beaver.start = function()
{
	Beaver.Loader.addModuleToQueue("user");
	Beaver.Loader.start( function(){
		
		Beaver.Modules.User.onLoginSuccess = function()
		{
			Beaver.Modules.User.hideLoginScreen();
			if( !Beaver.applicationStarted ) Beaver.startApplication();
		}
		
		Beaver.sessionCheckLoop();
	});
};

Beaver.sessionCheckLoop = function()	
{
	// add overtime to session lifetime
	var lifetime = Beaver.Modules.User.sessionLifetime * 1000 + 5000;
	
	// add pooing provider to check the session
	Ext.Direct.addProvider({
        type:'polling',
        url: '/module/user/checksession',
		interval: lifetime
	});

	// event to check the session
	Ext.Direct.on('checksession', function( event )
	{
		if ( event.data == false ) {
			Beaver.Modules.User.showLoginScreen();
		} else {
			Beaver.Modules.User.hideLoginScreen();
			if( !Beaver.applicationStarted ) Beaver.startApplication();
		}
	});
}

Beaver.startApplication = function()
{
	Beaver.applicationStarted = true;
}